package com.example.net.socket.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhaoyunlong
 * @date 2020/11/9
 * @description
 */
public class SocketServiceImpl {

    public static void main(String[] args) {

        //服务端需要使用serverSocket来开放本体的端口
        try (ServerSocket serverSocket = new ServerSocket(8081);
             Socket accept = serverSocket.accept();
             InputStream inputStream = accept.getInputStream()) {

            /**
             * 接收客户端的消息
             */
            byte[] data = new byte[1024];
            int read;
            while ((read = inputStream.read(data)) != -1) {
                System.out.println("从客户端接收的消息是："  + new String(data, 0, read));
            }
            // 截断输出流   告诉输入已经结束
            accept.shutdownInput();

            /**
             * 向客户端发送消息
             */
            OutputStream outputStream = accept.getOutputStream();
            String outputData = "hello, 您好 客户端！";
            outputStream.write(outputData.getBytes());
            outputStream.flush();
            // 截断输出流   告诉输出已经结束
            accept.shutdownOutput();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
